<?php

namespace app\admin\controller\pms;

use app\common\controller\Backend;
use think\Db;

/**
 * 客栈会员信息
 *
 * @icon fa fa-circle-o
 */
class Pmsreport extends Backend
{
    
    /**
     * Pmsuser模型对象
     * @var \app\admin\model\Pmsuser
     */
    protected $model = null;
    protected $prefix = '';

    public function _initialize()
    {
        parent::_initialize();
        $this->prefix = config('database.prefix');
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 查看
     */
    public function index()
    {
        $conf = new \app\admin\model\Pmsconfig;
        $oi = new \app\admin\model\Pmsorderinfo;
        $resi = new \app\admin\model\Pmsreserveinfo;
        $ri = new \app\admin\model\Pmsroominfo;
        $rt = new \app\admin\model\Pmsroomtype;
        $op = new \app\admin\model\Pmsorderpayment;
        $opl = new \app\admin\model\Pmsorderpeoplelist;
        $roomitems = new \app\admin\model\Pmsroomitems;
        $servicesitems = new \app\admin\model\Pmsservicesitems;
        $oroomitems = new \app\admin\model\Pmsorderroomitems;
        $oservicesitems = new \app\admin\model\Pmsorderservicesitems;
        $prefix = $this->prefix;

        $end_time = date('Y-m-d');
        $start_time = date('Y-m-d', strtotime('-7 day', strtotime($end_time))) . ' 00:00:00';
        $end_time .= ' 23:59:59';

        if ($this->request->isAjax()) {
            $search_dates = input('search_dates', '2021-05-01 00:00:00 - 2021-05-23 23:59:59');
            $search_datesSplit = explode(' - ', $search_dates);
            $start_time = $search_datesSplit[0];
            $end_time = $search_datesSplit[1];
            $day_count = round(abs((strtotime($end_time) - strtotime($start_time)) / 86400));



            $dates_where = array();
            $dates_where['createtime'] = array('between', array(strtotime($start_time), strtotime($end_time)));

            //房间数
            $room_total = $ri->where('state', 1)->count();
            //入住订单
            $order_total = $oi->field('id')->where('order_status in (0, 1)')->where($dates_where)->count();
            //入住率
            $occupancy_rate = $room_total > 0 ? number_format($order_total / ($day_count * $room_total) * 100, 2) : 0;
            //预订单
            $reserve_total = $resi->field('id')->where('reserve_status in (0, 1)')->where($dates_where)->count();
            //销售额
            $gmv_total = $oi->where('order_status in (0, 1)')->where($dates_where)->sum('gmv');

            //收款
            $payment_total = $op->where('state', 0)->where($dates_where)->sum('money');

            $echarts1 = array(
                'legend_data'=>array('订单', '预订单', '销售额'),
                'xAxis_data'=>array(),
                'series'=>array(
                    array(
                        'name'=>'订单',
                        'type'=>'line',
                        'yAxisIndex'=>0,
                        // 'smooth'=>true,
                        'data'=>array()
                    ),
                    array(
                        'name'=>'预订单',
                        'type'=>'line',
                        'yAxisIndex'=>0,
                        // 'smooth'=>true,
                        'data'=>array()
                    ),
                    array(
                        'name'=>'销售额',
                        'type'=>'bar',
                        'yAxisIndex'=>1,
                        'color'=>'#ee6666',
                        'data'=>array()
                    )
                )
            );


            //每天订单统计
            $oiGroupList = $oi->field("count(0) as C, FROM_UNIXTIME(createtime, '%Y-%m-%d') as createdate")->where('order_status in (0, 1)')->where($dates_where)->group('createdate')->select();

            $oiGroupObject = $this->pri_array_to_object($oiGroupList, 'createdate');

            //每天预订单统计
            $resiGroupList = $resi->field("count(0) as C, FROM_UNIXTIME(createtime, '%Y-%m-%d') as createdate")->where('reserve_status in (0, 1)')->where($dates_where)->group('createdate')->select();
            $resiGroupObject = $this->pri_array_to_object($resiGroupList, 'createdate');

            //每天销售额统计
            $oiGmvGroupList = $oi->field("sum(gmv) as gmv_sum, FROM_UNIXTIME(createtime, '%Y-%m-%d') as createdate")->where('order_status in (0, 1)')->where($dates_where)->group('createdate')->select();
            $oiGmvGroupObject = $this->pri_array_to_object($oiGmvGroupList, 'createdate');

            for($i=0;$i<9999;$i++)
            {
                $theDate = date('Y-m-d', strtotime('+'.$i.' day', strtotime($start_time)));
                array_push($echarts1['xAxis_data'], $theDate);
                $key = $theDate;

                isset($oiGroupObject[$key]) ? array_push($echarts1['series'][0]['data'], $oiGroupObject[$key]['C']) : array_push($echarts1['series'][0]['data'], 0);

                isset($resiGroupObject[$key]) ? array_push($echarts1['series'][1]['data'], $resiGroupObject[$key]['C']) : array_push($echarts1['series'][1]['data'], 0);

                isset($oiGmvGroupObject[$key]) ? array_push($echarts1['series'][2]['data'], floatval($oiGmvGroupObject[$key]['gmv_sum'])) : array_push($echarts1['series'][2]['data'], 0);


                if ($theDate == date('Y-m-d', strtotime($end_time)))
                {
                    break;
                }
            }

            //房型入住统计
            $echarts2 = array(
                'yAxis_data'=>array(),
                'series_data'=>array()
            );
            $oiGroupList = $oi->field('count(0) as C, room_type_id')
                ->where('order_status in (0, 1)')
                ->where($dates_where)
                ->group('room_type_id')
                ->select();
            if (count($oiGroupList))
            {
                foreach($oiGroupList as $item)
                {
                    $m = $rt->where('id', $item['room_type_id'])->find();
                    $room_type_name = $m ? $m['name'] : '';
                    array_push($echarts2['yAxis_data'], $room_type_name);
                    array_push($echarts2['series_data'], $item['C']);
                }
            }
            else
            {
                $roomtypeList = $rt->where('state', 1)->select();
                foreach($roomtypeList as $item)
                {
                    array_push($echarts2['yAxis_data'], $item['name']);
                    array_push($echarts2['series_data'], 0);
                }
            }

            //入住客人年纪统计
            $echarts3 = array(
                array('name'=>'50后', 'value'=>0),
                array('name'=>'60后', 'value'=>0),
                array('name'=>'70后', 'value'=>0),
                array('name'=>'80后', 'value'=>0),
                array('name'=>'90后', 'value'=>0),
                array('name'=>'00后', 'value'=>0),
                array('name'=>'其他', 'value'=>0),
            );

            $oplList = $opl->alias('opl')
                ->field('opl.person_no')
                ->join($prefix . 'pms_order_info oi', 'oi.id = opl.order_id')
                ->where(array('oi.createtime'=>array('between', array(strtotime($start_time), strtotime($end_time)))))
                ->where('oi.order_status in (0, 1)')
                ->where('opl.certificates_type', '身份证')
                ->group('opl.person_no')
                ->select();
            foreach($oplList as $item)
            {
                $birthdayY = '';
                if (strlen($item['person_no']) == 15)
                {
                    $birthdayY = subtr("19" . $item['person_no'], 6, 3);
                }
                else if(strlen($item['person_no']) == 18)
                {
                    $birthdayY = substr($item['person_no'], 6, 3);
                }

                switch ($birthdayY) {
                    case '195':
                        $echarts3[0]['value']++;
                        break;
                    case '196':
                        $echarts3[1]['value']++;
                        break;
                    case '197':
                        $echarts3[2]['value']++;
                        break;
                    case '198':
                        $echarts3[3]['value']++;
                        break;
                    case '199':
                        $echarts3[4]['value']++;
                        break;
                    case '200':
                        $echarts3[5]['value']++;
                        break;
                    default:
                        $echarts3[6]['value']++;
                        break;
                }
            }

            //房间物品使用统计
            $echarts4 = array(
                'yAxis_data'=>array(),
                'series_data'=>array()
            );
            $oroomitemsGroupList = $oroomitems->alias('oroomitems')
                ->field("sum(oroomitems.num) as sum_num, oroomitems.items_id")
                ->join($prefix . 'pms_order_info oi', 'oi.id = oroomitems.order_id')
                ->where(array('oi.createtime'=>array('between', array(strtotime($start_time), strtotime($end_time)))))
                ->where('oi.order_status in (0, 1)')
                ->group('items_id')
                ->select();
            if (count($oroomitemsGroupList))
            {
                foreach($oroomitemsGroupList as $item)
                {
                    $m = $roomitems->where('id', $item['items_id'])->find();
                    $item_name = $m ? $m['name'] : '';
                    array_push($echarts4['yAxis_data'], $item_name);
                    array_push($echarts4['series_data'], $item['sum_num']);
                }
            }
            else
            {
                $roomitemsList = $roomitems->where('state', 1)->select();
                foreach($roomitemsList as $item)
                {
                    array_push($echarts4['yAxis_data'], $item['name']);
                    array_push($echarts4['series_data'], 0);
                }
            }

            //服务使用统计
            $echarts5 = array(
                'yAxis_data'=>array(),
                'series_data'=>array()
            );
            $oservicesitemsGroupList = $oservicesitems->alias('oservicesitems')
                ->field("sum(oservicesitems.num) as sum_num, oservicesitems.services_items_id")
                ->join($prefix . 'pms_order_info oi', 'oi.id = oservicesitems.order_id')
                ->where(array('oi.createtime'=>array('between', array(strtotime($start_time), strtotime($end_time)))))
                ->where('oi.order_status in (0, 1)')
                ->group('services_items_id')
                ->select();
            if (count($oservicesitemsGroupList))
            {
                foreach($oservicesitemsGroupList as $item)
                {
                    $m = $servicesitems->where('id', $item['services_items_id'])->find();
                    $item_name = $m ? $m['name'] : '';
                    array_push($echarts5['yAxis_data'], $item_name);
                    array_push($echarts5['series_data'], $item['sum_num']);
                }
            }
            else
            {
                $servicesitemsList = $servicesitems->where('state', 1)->select();
                foreach($servicesitemsList as $item)
                {
                    array_push($echarts5['yAxis_data'], $item['name']);
                    array_push($echarts5['series_data'], 0);
                }
            }

            return json(array(
                'order_total'=>number_format($order_total),
                'occupancy_rate'=>$occupancy_rate,
                'reserve_total'=>number_format($reserve_total),
                'gmv_total'=>number_format($gmv_total),
                'payment_total'=>number_format($payment_total),
                'echarts1'=>$echarts1,
                'echarts2'=>$echarts2,
                'echarts3'=>$echarts3,
                'echarts4'=>$echarts4,
                'echarts5'=>$echarts5
            ));
        }

        $today_dates = date('Y-m-d') . ' 00:00:00 - ' . date('Y-m-d') . ' 23:59:59';
        $yesterday_dates = date('Y-m-d', strtotime('-1 day')) . ' 00:00:00 - ' . date('Y-m-d', strtotime('-1 day')) . ' 23:59:59';
        $last7days_dates = date('Y-m-d', strtotime('-6 day')) . ' 00:00:00 - ' . date('Y-m-d') . ' 23:59:59';
        $last30days_dates = date('Y-m-d', strtotime('-29 day')) . ' 00:00:00 - ' . date('Y-m-d') . ' 23:59:59';
        $lastmonth_dates = date('Y-m-01', strtotime('-1 month')) . ' 00:00:00 - ' . date('Y-m-t', strtotime('-1 month')) . ' 23:59:59';
        $thismonth_dates = date('Y-m-01') . '-01 00:00:00 - ' . date('Y-m-t') . ' 23:59:59';

        $this->view->assign("today_dates", $today_dates);
        $this->view->assign("yesterday_dates", $yesterday_dates);
        $this->view->assign("last7days_dates", $last7days_dates);
        $this->view->assign("last30days_dates", $last30days_dates);
        $this->view->assign("lastmonth_dates", $lastmonth_dates);
        $this->view->assign("thismonth_dates", $thismonth_dates);

        $this->view->assign("end_time", $end_time);
        $this->view->assign("end_time", $end_time);
        $this->view->assign("end_time", $end_time);

        $this->view->assign("start_time", $start_time);
        $this->view->assign("end_time", $end_time);
        return $this->view->fetch();
    }

    private function pri_array_to_object($data, $field)
    {
        $re = array();
        if (count($data))
        {
            foreach($data as $item)
            {
                $key = $item[$field];
                $re[$key] = $item;
            }
        }

        return $re;
    }

}
